import { debounce } from '../utils/utils.js';
let win;

const openMenu = (option) => {
  let { x, y, url } = option;
  const ubWindow = utools.createBrowserWindow(
    "./" + url + "/menu.html",
    {
      title: "编辑",
      skipTaskbar: true,
      frame: false,
      backgroundColor: "rgba(255,255,255,0)",
      transparent: true,
      titleBarStyle: "hidden",
      resizable: false,
      width: 110,
      x,
      y,
      webPreferences: {
        preload: "./" + url + "/preload.js",
      },
    },
    () => {
      ubWindow.show();
      ubWindow.setBackgroundColor("rgba(255,255,255,0)");
      // ubWindow.webContents.openDevTools();
      ipcRenderer.sendTo(ubWindow.webContents.id, "senderId");
      // let data = window.getData();
      // ipcRenderer.sendTo(ubWindow.webContents.id, "init", data);
      window.isAlwaysOnTop()
      ubWindow.setAlwaysOnTop(true, 'pop-up-menu')
    }
  );
  win = ubWindow;
};

window.closeMenu = () => {
  win.destroy();
  win = null
}

if(window.ipcRenderer){
  window.ipcRenderer.on("blur", () => {
    window.closeMenu();
  });

  window.ipcRenderer.on("edit", () => {
    window.getPosition();
    window.closeMenu();
  });


  window.ipcRenderer.on("top", () => {
    window.alwaysOnTop();
    window.closeMenu();
  });

  window.ipcRenderer.on("delete", () => {
    window.closeWin()
    window.closeMenu();
  });

  window.ipcRenderer.on("isAlwaysOnTop", (evet, bool) => {
    if(win){
      window.ipcRenderer.sendTo(win.webContents.id, "isAlwaysOnTop", bool);
    }
  });


}

document.documentElement.oncontextmenu = (e) => {
  e.preventDefault();
  const { x, y } = window.utools.getCursorScreenPoint();

  if (win) {
    win.setPosition(x,y)
  } else {
    let url = location.href.split("/").at(-2);

    openMenu({
      x,
      y,
      url,
    })
  }
};


// 窗口变化
window.addEventListener(
 "resize",
 debounce(() => {
   if (window.sendSaveData) {
     let data = window.getData();
     window.sendSaveData(data);
   }
 }, 500)
);
